﻿/*
    Copyright Multi-Soft co.2009 
*/

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

namespace Rmlife.Common
{
    /// <summary>
    /// Xml序列化工具类
    /// </summary>
    public class SerializationHelper
    {
        private static Dictionary<int, XmlSerializer> serializer_dict = new Dictionary<int, XmlSerializer>();
        public static XmlSerializer GetSerializer(Type t)
        {
            int type_hash = t.GetHashCode();

            if (!serializer_dict.ContainsKey(type_hash))
                serializer_dict.Add(type_hash, new XmlSerializer(t));

            return serializer_dict[type_hash];
        }

        /// <summary>
        /// 读取文件，依类型反序列化读入一个对象
        /// </summary>
        /// <param name="type"></param>
        /// <param name="filename"></param>
        /// <returns></returns>
        public static object Load(Type type, string filename)
        {
            FileStream sm = null;
            object obj;
            try
            {
                sm = new FileStream(filename, FileMode.Open, FileAccess.Read);
                obj = new XmlSerializer(type).Deserialize(sm);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (sm != null)
                {
                    sm.Close();
                }
            }
            return obj;
        }

        /// <summary>
        /// 保存文件，按对象类型进行序列化后保存为文件
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="filename"></param>
        /// <returns></returns>
        public static bool Save(object obj, string filename)
        {
            return Save(obj, filename, null);
        }
        /// <summary>
        /// 保存文件，按对象类型进行序列化后保存为文件
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="filename"></param>
        /// <returns></returns>
        public static bool Save(object obj, string filename, XmlAttributeOverrides attrOver)
        {
            if (obj == null)
                return false;

            bool ret = false;
            FileStream sm = null;
            try
            {
                if (File.Exists(filename))
                    File.SetAttributes(filename, FileAttributes.Normal);

                sm = new FileStream(filename, FileMode.Create);
                new XmlSerializer(obj.GetType(), attrOver).Serialize(sm, obj);
                ret = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (sm != null)
                {
                    sm.Close();
                }
            }
            return ret;
        }

        /// <summary>
        /// 串行化对象为字符串
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string Serialize(object obj)
        {
            string returnStr = "";
#if NET1
            XmlSerializer serializer = new XmlSerializer(obj.GetType());
#else

            XmlSerializer serializer = GetSerializer(obj.GetType());
#endif
            MemoryStream ms = new MemoryStream();
            XmlTextWriter xtw = null;
            StreamReader sr = null;
            try
            {
                xtw = new System.Xml.XmlTextWriter(ms, Encoding.UTF8);
                xtw.Formatting = System.Xml.Formatting.Indented;
                serializer.Serialize(xtw, obj);
                ms.Seek(0, SeekOrigin.Begin);
                sr = new StreamReader(ms);
                returnStr = sr.ReadToEnd();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (xtw != null)
                    xtw.Close();
                if (sr != null)
                    sr.Close();
                ms.Close();
            }
            return returnStr;
        }

        /// <summary>
        /// 字符串按类型反串行化为对象
        /// </summary>
        /// <param name="s"></param>
        /// <param name="t"></param>
        /// <returns></returns>
        public static object Deserialize(string s, Type type)
        {
            byte[] b = System.Text.Encoding.UTF8.GetBytes(s);
            try
            {
#if NET1
                XmlSerializer serializer = new XmlSerializer(type);
#else
                XmlSerializer serializer = GetSerializer(type);
#endif
                return serializer.Deserialize(new MemoryStream(b));
            }
            catch
            {
                return null;
            }
        }
    }
}
